
package edu.hm.devcamp.providers;

import java.net.URI;
import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.util.Log;
import edu.hm.devcamp.presentation.activities.PoiMap;

/**
 * POI Content Provider modelled after
 * http://thinkandroid.wordpress.com/2010/01/
 * 13/writing-your-own-contentprovider/
 * 
 * @author Marco
 */
public class PoiProvider extends ContentProvider {
    /**
     * tag for Log.w();
     */
    private static final String TAG = "PoiProvider";

    /**
     * the database file
     */
    private static final String DATABASE_NAME = "poi.db";

    /**
     * increment this after scheme changes
     */
    private static final int DATABASE_VERSION = 3;

    /**
     * table for the POIs
     */
    private static final String POIS_TABLE_NAME = "pois";

    /**
     * authority for URIMatcher
     */
    public static final String AUTHORITY = "edu.hm.devcamp.providers.PoiProvider";

    /**
     * the URI to use to access the provider
     */
    public static final Uri CONTENT_URI = Uri.parse(AUTHORITY);

    /**
     * the (static) URIMatcher
     */
    private static final UriMatcher sUriMatcher;

    /**
     * return code for URIMatcher: the Uri represents a POI
     */
    private static final int POIS = 1;

    /**
     * here we store the table column projection map for querying POIs
     */
    private static HashMap<String, String> poiProjectionMap;

    /**
     * helper functions (setup, scheme upgrade) for SQLite
     * 
     * @author Marco
     */
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.d(TAG, "Creating database");
            db.execSQL("CREATE TABLE " + POIS_TABLE_NAME + " (" + Pois.POI_ID
                    + " INTEGER PRIMARY KEY," + Pois.SOURCE + " VARCHAR(255)," + Pois.EXTERNAL_ID
                    + " VARCHAR(255)," + Pois.CATEGORY + " VARCHAR(255)," + Pois.NAME
                    + " LONGTEXT," + Pois.DESC + " VARCHAR(500)," + Pois.STREET + " VARCHAR(255),"
                    + Pois.STREETNUM + " VARCHAR(10)," + Pois.ZIPCODE + " VARCHAR(7)," + Pois.CITY
                    + " LONGTEXT," + Pois.COORD_LON + " VARCHAR(15)," + Pois.COORD_LAT
                    + " VARCHAR(15)," + Pois.OPENING_TIMES + " VARCHAR(255)," + Pois.URL
                    + " VARCHAR(1024)" + ");");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
                    + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + POIS_TABLE_NAME);
            onCreate(db);
        }
    }

    /**
     * an instance of the private subclass {@link DatabaseHelper}
     */
    private static DatabaseHelper dbHelper;

    /**
     * delete an entry from the POI DB
     * 
     * @param uri which table
     * @param where just like the WHERE clause in a SQL statement, just without
     *            the WHERE
     * @param whereArgs WHERE arguments if you use ? as placeholder in WHERE
     *            clause
     * @return the number of rows deleted
     */
    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
            case POIS:
                count = db.delete(POIS_TABLE_NAME, where, whereArgs);
                break;

            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    /**
     * get the content type for a specific URI
     * 
     * @param uri the URI requested
     * @return the content type
     * @throws IllegalArgumentException for unknown URIs
     */
    @Override
    public String getType(Uri uri) throws IllegalArgumentException {
        switch (sUriMatcher.match(uri)) {
            case POIS:
                return Pois.CONTENT_TYPE;

            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    /**
     * insert a new row into the table specified by the URI
     * 
     * @param uri where to put the row
     * @param initialValues the data for the columns
     * @return the URI of this specific row
     */
    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
        if (PoiMap.LOG_D) {
            Log.d(TAG, "Insert URI: " + uri.toString());
        }
        if (sUriMatcher.match(uri) != POIS) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long rowId = db.insert(POIS_TABLE_NAME, Pois.DESC, values);
        if (rowId > 0) {
            Uri newUri = ContentUris.withAppendedId(uri, rowId);
            getContext().getContentResolver().notifyChange(newUri, null);
            return newUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
    }

    /**
     * insert a new array of rows into the table specified by the URI
     * 
     * @param uri where to put the row
     * @param initialValues the data for the columns
     * @return the URI of this specific row
     */
    public static int insertLocal(ContentValues[] valuesArray) {
        
        int i = 0;
        
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.beginTransaction();
        for (ContentValues values: valuesArray) {
            db.insert(POIS_TABLE_NAME, Pois.DESC, values);
            i++;
        }
        db.setTransactionSuccessful();
        db.endTransaction();

        return i;
    }
    
    /**
     * gets called as constructor and inits the dbHelper
     * 
     * @return always true
     */
    @Override
    public boolean onCreate() {
        dbHelper = new DatabaseHelper(getContext());
        return true;
    }

    /**
     * run a query
     * 
     * @param uri what content to query
     * @param projection what rows to return
     * @param selection just like the WHERE clause in a SQL statement, just
     *            without the WHERE
     * @param selectionArgs WHERE arguments if you use ? as placeholder in where
     * @param sortOrder how to sort the rows
     * @return {@link Cursor} object to fetch the returned rows
     */
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        switch (sUriMatcher.match(uri)) {
            case POIS:
                qb.setTables(POIS_TABLE_NAME);
                qb.setProjectionMap(poiProjectionMap);
                break;

            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);

        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    /**
     * run a query
     * 
     * @param uri what content to query
     * @param projection what rows to return
     * @param selection just like the WHERE clause in a SQL statement, just
     *            without the WHERE
     * @param selectionArgs WHERE arguments if you use ? as placeholder in where
     * @param sortOrder how to sort the rows
     * @return {@link Cursor} object to fetch the returned rows
     */
     public static Cursor queryLocal(String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        qb.setTables(POIS_TABLE_NAME);
        qb.setProjectionMap(poiProjectionMap);              

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);

        return c;
    }
    
    /**
     * update a row in the table
     * 
     * @param uri which table the row is in
     * @param values the new data
     * @param where just like the WHERE clause in a SQL statement, just without
     *            the WHERE
     * @param whereArgs WHERE arguments if you use ? as placeholder in where
     * @return the number of rows updated
     */
    @Override
    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
            case POIS:
                count = db.update(POIS_TABLE_NAME, values, where, whereArgs);
                break;

            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    /**
     * initialize the URIMatcher and the projection map
     */
    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(AUTHORITY, POIS_TABLE_NAME, POIS);

        poiProjectionMap = new HashMap<String, String>();
        poiProjectionMap.put(Pois.POI_ID, Pois.POI_ID);
        poiProjectionMap.put(Pois.SOURCE, Pois.SOURCE);
        poiProjectionMap.put(Pois.EXTERNAL_ID, Pois.EXTERNAL_ID);
        poiProjectionMap.put(Pois.CATEGORY, Pois.CATEGORY);
        poiProjectionMap.put(Pois.NAME, Pois.NAME);
        poiProjectionMap.put(Pois.DESC, Pois.DESC);
        poiProjectionMap.put(Pois.STREET, Pois.STREET);
        poiProjectionMap.put(Pois.STREETNUM, Pois.STREETNUM);
        poiProjectionMap.put(Pois.ZIPCODE, Pois.ZIPCODE);
        poiProjectionMap.put(Pois.CITY, Pois.CITY);
        poiProjectionMap.put(Pois.COORD_LAT, Pois.COORD_LAT);
        poiProjectionMap.put(Pois.COORD_LON, Pois.COORD_LON);
        poiProjectionMap.put(Pois.URL, Pois.URL);
        poiProjectionMap.put(Pois.OPENING_TIMES, Pois.OPENING_TIMES);

    }
}
